<template>
  <div class="system-management-container">
    <el-card class="page-header-card">
      <div class="page-header">
        <div class="page-title">
          <h2>系统管理</h2>
          <p>管理系统配置和收费标准</p>
        </div>
      </div>
    </el-card>
    
    <!-- 系统管理选项卡 -->
    <el-card class="tab-card">
      <el-tabs v-model="activeTab">
        <el-tab-pane label="收费标准管理" name="feeStandard">
          <!-- 收费标准管理 -->
          <div class="fee-standard-section">
            <div class="section-header">
              <div class="section-title">收费标准列表</div>
              <el-button type="primary" @click="handleAddFeeStandard">
                <el-icon><Plus /></el-icon>新增收费标准
              </el-button>
            </div>
            
            <!-- 收费标准表格 -->
            <el-table 
              :data="feeStandards" 
              style="width: 100%; margin-top: 20px;" 
              border 
              v-loading="loading"
            >
              <el-table-column prop="id" label="ID" width="80" />
              <el-table-column prop="name" label="标准名称" min-width="120" />
              <el-table-column label="车位类型" min-width="100">
                <template #default="scope">
                  <el-tag :type="getSpaceTypeTag(scope.row.spaceType)">
                    {{ getSpaceTypeText(scope.row.spaceType) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="收费类型" min-width="100">
                <template #default="scope">
                  <span>{{ getFeeTypeText(scope.row.feeType) }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="feeAmount" label="费用金额" min-width="100">
                <template #default="scope">
                  <span>¥{{ scope.row.feeAmount != null ? Number(scope.row.feeAmount).toFixed(2) : '0.00' }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="freeMinutes" label="免费时长(分钟)" min-width="120" />
              <el-table-column prop="dayCap" label="日封顶金额" min-width="120">
                <template #default="scope">
                  <span>¥{{ scope.row.dayCap != null ? Number(scope.row.dayCap).toFixed(2) : '0.00' }}</span>
                </template>
              </el-table-column>
              <el-table-column label="生效时间" min-width="180">
                <template #default="scope">
                  <div>{{ formatDateTime(scope.row.startTime) }}</div>
                  <div>至</div>
                  <div>{{ formatDateTime(scope.row.endTime) }}</div>
                </template>
              </el-table-column>
              <el-table-column label="状态" width="120">
                <template #default="{ row }">
                  <el-switch
                    v-model="row.status"
                    :active-value="1"
                    :inactive-value="0"
                    @change="() => handleStatusChange(row)"
                  />
                </template>
              </el-table-column>
              <el-table-column label="操作" width="150" fixed="right">
                <template #default="scope">
                  <el-button type="primary" size="small" @click="handleEditFeeStandard(scope.row)">
                    编辑
                  </el-button>
                  <el-button type="danger" size="small" @click="handleDeleteFeeStandard(scope.row)">
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            
            <!-- 分页 -->
            <div class="pagination-container">
              <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :page-sizes="[10, 20, 50, 100]"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>
          </div>
        </el-tab-pane>
        
        <el-tab-pane label="系统配置" name="systemConfig">
          <!-- 系统配置 -->
          <div class="system-config-section">
            <el-form :model="systemConfig" label-width="180px">
              <el-form-item label="系统名称">
                <el-input v-model="systemConfig.systemName" placeholder="请输入系统名称" />
              </el-form-item>
              
              <el-form-item label="平台联系电话">
                <el-input v-model="systemConfig.contactPhone" placeholder="请输入平台联系电话" />
              </el-form-item>
              
              <el-form-item label="服务时间设置">
                <el-time-picker
                  v-model="systemConfig.openTime"
                  placeholder="开始时间"
                  format="HH:mm"
                  style="width: 180px; margin-right: 10px;"
                />
                <span>至</span>
                <el-time-picker
                  v-model="systemConfig.closeTime"
                  placeholder="结束时间"
                  format="HH:mm"
                  style="width: 180px; margin-left: 10px;"
                />
              </el-form-item>
              
              <el-form-item label="车牌自动识别时间">
                <el-input-number v-model="systemConfig.recognitionTime" :min="1" :max="10" /> 秒
              </el-form-item>
              
              <el-form-item label="预约有效时间">
                <el-input-number v-model="systemConfig.reservationValidTime" :min="5" :max="60" /> 分钟
              </el-form-item>
              
              <el-form-item>
                <el-button type="primary" @click="saveSystemConfig">保存配置</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    
    <!-- 添加/编辑收费标准对话框 -->
    <el-dialog 
      v-model="feeStandardDialogVisible" 
      :title="dialogType === 'add' ? '添加收费标准' : '编辑收费标准'"
      width="600px"
    >
      <el-form :model="feeStandardForm" :rules="feeStandardRules" ref="feeStandardFormRef" label-width="120px">
        <el-form-item label="标准名称" prop="name">
          <el-input v-model="feeStandardForm.name" placeholder="请输入标准名称" />
        </el-form-item>
        
        <el-form-item label="车位类型" prop="spaceType">
          <el-select v-model="feeStandardForm.spaceType" placeholder="请选择车位类型" style="width: 100%;">
            <el-option :value="0" label="普通车位" />
            <el-option :value="1" label="固定车位" />
            <el-option :value="2" label="访客车位" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="收费类型" prop="feeType">
          <el-select v-model="feeStandardForm.feeType" placeholder="请选择收费类型" style="width: 100%;">
            <el-option :value="0" label="小时" />
            <el-option :value="1" label="天" />
            <el-option :value="2" label="月" />
            <el-option :value="3" label="年" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="费用金额" prop="feeAmount">
          <el-input-number v-model="feeStandardForm.feeAmount" :precision="2" :step="0.1" :min="0" style="width: 100%;" />
        </el-form-item>
        
        <el-form-item label="免费时长(分钟)" prop="freeMinutes">
          <el-input-number v-model="feeStandardForm.freeMinutes" :min="0" :step="5" style="width: 100%;" />
        </el-form-item>
        
        <el-form-item label="日封顶金额" prop="dayCap">
          <el-input-number v-model="feeStandardForm.dayCap" :precision="2" :step="1" :min="0" style="width: 100%;" />
        </el-form-item>
        
        <el-form-item label="生效时间" prop="timeRange">
          <el-date-picker
            v-model="feeStandardForm.timeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 100%;"
          />
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="feeStandardForm.status"
            :active-value="1"
            :inactive-value="0"
            active-text="启用"
            inactive-text="禁用"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="feeStandardDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitFeeStandard">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Delete, Edit } from '@element-plus/icons-vue'
import { getFeeStandardList, getFeeStandardDetail, addFeeStandard, updateFeeStandard, deleteFeeStandard, changeFeeStandardStatus, getSystemConfig, updateSystemConfig } from '@/api/system'

// 当前选中的选项卡
const activeTab = ref('feeStandard')

// 加载状态
const loading = ref(false)

// 分页参数
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 查询参数
const queryParams = ref({
  page: currentPage,
  size: pageSize,
  name: '',
  spaceType: '',
  feeType: '',
  status: ''
})

// 收费标准列表数据
const feeStandards = ref([])

// 系统配置数据
const systemConfig = reactive({
  systemName: '',
  contactPhone: '',
  openTime: null,
  closeTime: null,
  recognitionTime: 3,
  reservationValidTime: 15,
  defaultPassword: ''
})

// 对话框相关
const feeStandardDialogVisible = ref(false)
const dialogType = ref('add') // 'add' 或 'edit'
const feeStandardFormRef = ref(null)

// 收费标准表单
const feeStandardForm = reactive({
  id: null,
  name: '',
  spaceType: '',
  feeType: '',
  feeAmount: 0,
  freeMinutes: 0,
  dayCap: 0,
  timeRange: [],
  status: 1
})

// 表单验证规则
const feeStandardRules = {
  name: [{ required: true, message: '请输入标准名称', trigger: 'blur' }],
  spaceType: [{ required: true, message: '请选择车位类型', trigger: 'change' }],
  feeType: [{ required: true, message: '请选择收费类型', trigger: 'change' }],
  feeAmount: [{ required: true, message: '请输入费用金额', trigger: 'blur' }],
  timeRange: [{ required: true, message: '请选择生效时间范围', trigger: 'change' }]
}

// 生命周期钩子
onMounted(() => {
  fetchFeeStandards()
  fetchSystemConfig()
})

// 获取收费标准列表
const fetchFeeStandards = async () => {
  loading.value = true
  try {
    // 构建查询参数
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      name: queryParams.value.name || undefined,
      spaceType: queryParams.value.spaceType || undefined,
      feeType: queryParams.value.feeType || undefined,
      status: queryParams.value.status || undefined
    }
    
    // 使用真实API调用
    const response = await getFeeStandardList(params);
    if (response.code === 200) {
      feeStandards.value = response.data.records || [];
      total.value = response.data.total || 0;
    } else {
      ElMessage.error(response.message || '获取收费标准列表失败');
    }
  } catch (error) {
    console.error('获取收费标准列表出错:', error);
    ElMessage.error('获取收费标准列表失败，请稍后重试');
  } finally {
    loading.value = false;
  }
}

// 获取系统配置
const fetchSystemConfig = async () => {
  try {
    const response = await getSystemConfig();
    if (response.code === 200) {
      const config = response.data;
      
      // 使用返回的系统配置更新本地状态
      systemConfig.systemName = config.systemName;
      systemConfig.contactPhone = config.contactPhone;
      systemConfig.recognitionTime = config.recognitionTime;
      systemConfig.reservationValidTime = config.reservationValidTime;
      systemConfig.defaultPassword = config.defaultPassword;
      
      // 处理时间格式
      if (config.openTime) {
        const [hours, minutes] = config.openTime.split(':');
        systemConfig.openTime = new Date();
        systemConfig.openTime.setHours(parseInt(hours), parseInt(minutes), 0);
      }
      
      if (config.closeTime) {
        const [hours, minutes] = config.closeTime.split(':');
        systemConfig.closeTime = new Date();
        systemConfig.closeTime.setHours(parseInt(hours), parseInt(minutes), 0);
      }
    } else {
      ElMessage.error(response.message || '获取系统配置失败');
    }
  } catch (error) {
    console.error('获取系统配置失败:', error);
    ElMessage.error('获取系统配置失败，请稍后重试');
  }
}

// 获取车位类型标签样式
const getSpaceTypeTag = (type) => {
  const types = {
    0: 'info',   // 普通
    1: 'success', // 固定
    2: 'warning'  // 访客
  }
  return types[type] || 'info'
}

// 获取车位类型文本
const getSpaceTypeText = (type) => {
  const types = {
    0: '普通车位',
    1: '固定车位',
    2: '访客车位'
  }
  return types[type] || '未知类型'
}

// 获取收费类型文本
const getFeeTypeText = (type) => {
  const types = {
    0: '小时',
    1: '天',
    2: '月',
    3: '年'
  }
  return types[type] || '未知类型'
}

// 格式化日期时间
const formatDateTime = (date) => {
  if (!date) return '';
  const d = new Date(date);
  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, '0');
  const day = String(d.getDate()).padStart(2, '0');
  const hours = String(d.getHours()).padStart(2, '0');
  const minutes = String(d.getMinutes()).padStart(2, '0');
  const seconds = String(d.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

// 处理状态变更
const handleStatusChange = async (row) => {
  try {
    const response = await changeFeeStandardStatus({
      id: row.id,
      status: row.status
    });
    if (response.code === 200) {
      ElMessage.success(`${row.status === 1 ? '启用' : '禁用'}成功`);
      fetchFeeStandards();
    } else {
      ElMessage.error(response.message || '更改状态失败');
      // 恢复原状态
      row.status = row.status === 1 ? 0 : 1;
    }
  } catch (error) {
    console.error('更改收费标准状态出错:', error);
    ElMessage.error('更改收费标准状态失败，请稍后重试');
    // 恢复原状态
    row.status = row.status === 1 ? 0 : 1;
  }
}

// 处理添加收费标准
const handleAddFeeStandard = () => {
  dialogType.value = 'add'
  resetFeeStandardForm()
  feeStandardDialogVisible.value = true
}

// 处理编辑收费标准
const handleEditFeeStandard = (row) => {
  dialogType.value = 'edit'
  resetFeeStandardForm()
  
  // 填充表单数据
  feeStandardForm.id = row.id;
  feeStandardForm.name = row.name;
  feeStandardForm.spaceType = row.spaceType;
  feeStandardForm.feeType = row.feeType;
  feeStandardForm.feeAmount = row.feeAmount;
  feeStandardForm.freeMinutes = row.freeMinutes;
  feeStandardForm.dayCap = row.dayCap;
  feeStandardForm.status = row.status;
  
  // 设置时间范围
  feeStandardForm.timeRange = [
    new Date(row.startTime),
    new Date(row.endTime)
  ];
  
  feeStandardDialogVisible.value = true
}

// 处理删除收费标准
const handleDeleteFeeStandard = (row) => {
  ElMessageBox.confirm('确定要删除该收费标准吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      const response = await deleteFeeStandard(row.id);
      if (response.code === 200) {
        ElMessage.success('删除成功');
        fetchFeeStandards();
      } else {
        ElMessage.error(response.message || '删除失败');
      }
    } catch (error) {
      console.error('删除收费标准出错:', error);
      ElMessage.error('删除收费标准失败，请稍后重试');
    }
  }).catch(() => {});
}

// 重置收费标准表单
const resetFeeStandardForm = () => {
  if (feeStandardFormRef.value) {
    feeStandardFormRef.value.resetFields()
  }
  
  feeStandardForm.id = null
  feeStandardForm.name = ''
  feeStandardForm.spaceType = ''
  feeStandardForm.feeType = ''
  feeStandardForm.feeAmount = 0
  feeStandardForm.freeMinutes = 0
  feeStandardForm.dayCap = 0
  feeStandardForm.timeRange = []
  feeStandardForm.status = 1
}

// 提交收费标准
const submitFeeStandard = () => {
  feeStandardFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const formData = { ...feeStandardForm };
        // 处理时间范围
        if (formData.timeRange && formData.timeRange.length === 2) {
          // 转换为yyyy-MM-dd HH:mm:ss格式
          formData.startTime = formatDateTime(formData.timeRange[0]);
          formData.endTime = formatDateTime(formData.timeRange[1]);
        }
        delete formData.timeRange;
        
        // 构造API数据
        const apiData = {
          id: formData.id,
          name: formData.name,
          spaceType: formData.spaceType,
          feeType: formData.feeType,
          feeAmount: formData.feeAmount,
          freeMinutes: formData.freeMinutes,
          dayCap: formData.dayCap,
          startTime: formData.startTime,
          endTime: formData.endTime,
          status: formData.status
        };
        
        let response;
        if (formData.id) {
          // 更新
          response = await updateFeeStandard(apiData);
        } else {
          // 新增
          response = await addFeeStandard(apiData);
        }
        
        if (response.code === 200) {
          ElMessage.success('保存成功');
          feeStandardDialogVisible.value = false;
          fetchFeeStandards();
        } else {
          ElMessage.error(response.message || '保存失败');
        }
      } catch (error) {
        console.error('保存收费标准出错:', error);
        ElMessage.error('保存收费标准失败，请稍后重试');
      }
    }
  });
}

// 保存系统配置
const saveSystemConfig = async () => {
  try {
    // 准备提交数据
    const configData = {
      systemName: systemConfig.systemName,
      contactPhone: systemConfig.contactPhone,
      recognitionTime: systemConfig.recognitionTime,
      reservationValidTime: systemConfig.reservationValidTime,
      defaultPassword: systemConfig.defaultPassword
    };
    
    // 处理时间格式
    if (systemConfig.openTime) {
      const hours = systemConfig.openTime.getHours().toString().padStart(2, '0');
      const minutes = systemConfig.openTime.getMinutes().toString().padStart(2, '0');
      configData.openTime = `${hours}:${minutes}`;
    }
    
    if (systemConfig.closeTime) {
      const hours = systemConfig.closeTime.getHours().toString().padStart(2, '0');
      const minutes = systemConfig.closeTime.getMinutes().toString().padStart(2, '0');
      configData.closeTime = `${hours}:${minutes}`;
    }
    
    const response = await updateSystemConfig(configData);
    if (response.code === 200) {
      ElMessage.success('系统配置保存成功');
    } else {
      ElMessage.error(response.message || '保存系统配置失败');
    }
  } catch (error) {
    console.error('保存系统配置失败:', error);
    ElMessage.error('保存系统配置失败，请稍后重试');
  }
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchFeeStandards()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchFeeStandards()
}
</script>

<style scoped>
.system-management-container {
  padding: 20px;
  min-height: calc(100vh - 180px);
}

.page-header-card {
  margin-bottom: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-title h2 {
  margin: 0 0 5px 0;
  font-size: 22px;
}

.page-title p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.tab-card {
  margin-bottom: 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-title {
  font-size: 18px;
  font-weight: bold;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

@media screen and (max-width: 768px) {
  .el-pagination {
    justify-content: center !important;
  }
  
  .card-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .header-actions {
    margin-top: 10px;
    display: flex;
    width: 100%;
  }
  
  .header-actions .el-button {
    flex: 1;
  }
  
  .dialog-footer {
    display: flex;
    flex-direction: column;
    gap: 10px;
  }
  
  .dialog-footer .el-button {
    width: 100%;
  }
}

@media screen and (max-width: 576px) {
  .system-management-container {
    padding: 10px;
  }
  
  .tab-card {
    margin-bottom: 10px;
  }
  
  .system-config-section .el-form-item {
    margin-bottom: 15px;
  }
  
  .el-date-picker {
    width: 100% !important;
  }
}
</style> 